from flask import Blueprint, request, abort
from flask_restful import Resource, Api, reqparse
from models import Community_PostModel, PostComment, PostLike
from exts import db
from datetime import datetime

# 创建蓝图
post_action_bp = Blueprint('post_action', __name__)
api = Api(post_action_bp)

class PostLikeResource(Resource):
    def post(self, post_id, user_id):
        post = Community_PostModel.query.get(post_id)
        if not post:
            abort(404, message='Post not found')
        
        like = PostLike.query.filter_by(post_id=post_id, user_id=user_id).first()
        if like:
            return {'message': 'Already liked'}, 400
            
        like = PostLike(post_id=post_id, user_id=user_id)
        db.session.add(like)
        post.like_count += 1
        db.session.commit()
        return {'message': 'Liked successfully'}

class PostCommentResource(Resource):
    def post(self, post_id, user_id):
        parser = reqparse.RequestParser()
        parser.add_argument('content', type=str, required=True)
        data = parser.parse_args()
        
        post = Community_PostModel.query.get(post_id)
        if not post:
            abort(404, message='Post not found')
        
        comment = PostComment(
            content=data['content'],
            post_id=post_id,
            user_id=user_id,
            create_time=datetime.now()
        )
        db.session.add(comment)
        post.comment_count += 1
        db.session.commit()
        return {'id': comment.id}, 201

# 注册路由
api.add_resource(PostLikeResource, '/post/<int:post_id>/like/<int:user_id>')
api.add_resource(PostCommentResource, '/post/<int:post_id>/comment/<int:user_id>') 